package com.ershui.blog.article.controller;

import com.ershui.blog.article.domain.CommonIds;
import com.ershui.blog.article.domain.LCategory;
import com.ershui.blog.article.service.LCategoryService;
import com.ershui.blog.system.domain.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 博文分类controller
 */
@RestController
@RequestMapping("/category")
public class CategoryController {
    public static final Logger log = LoggerFactory.getLogger(com.ershui.blog.article.controller.CategoryController.class);


    @Autowired
    private LCategoryService categoryService;


    @PostMapping("/add")
    @ResponseBody
    public AjaxResult AddCategory(LCategory category){
        try{
           int n=categoryService.insertSelective(category);
           return AjaxResult.sucess();
        }catch (Exception e){
            log.info("category add failed,reason:"+e.getMessage());
            return AjaxResult.error(e.getMessage());
        }
    }

    @PutMapping("/update")
    @ResponseBody
    public AjaxResult UpdateCategory(@RequestBody  LCategory category){
        try{
            categoryService.updateSelective(category);
            return AjaxResult.sucess();
        }catch (Exception e){
            log.info("category update failed,reason:"+e.getMessage());
            return AjaxResult.error(e.getMessage());
        }
    }

    @DeleteMapping("/delete")
    public AjaxResult DeleteCategorys(Long id){
        //查询是否有关联的文章，若有则不允许删除类别
        Long articleCount=categoryService.CountArticleByCategoryId(id);
        if(articleCount==0) {
            categoryService.deleteCategoryById(id);
            return AjaxResult.sucess("删除成功");
        }else{
            return AjaxResult.error("该类型有关联的文章，不能删除");
        }
    }

    @GetMapping("/select")
    @ResponseBody
    public  AjaxResult SelectCategorys(){
        List<LCategory> data=categoryService.selectCategorys();
        return AjaxResult.sucess("查询成功",data);
    }
}
